import 'dart:async';
import 'dart:io';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/provider/web_view_provider.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

import '../common_app_bar.dart' hide BackButton;
import 'package:provider/provider.dart';

class MyWebView extends StatefulWidget {
  final String url;
  final String title;
  final bool isShowProgress;
  final bool isHiddenTittle;

  const MyWebView(
      {Key key,
      this.url,
      this.title,
      this.isHiddenTittle = true,
      this.isShowProgress = false})
      : super(key: key);

  @override
  _MyWebViewState createState() => _MyWebViewState();
}

class _MyWebViewState extends State<MyWebView> with WidgetsBindingObserver {
  InAppWebViewController webView;
  ContextMenu contextMenu;
  StreamController<double> _progressCtl = StreamController();
  StreamController<String> _titleCtl = StreamController();
  bool showLoading = true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    contextMenu = ContextMenu(
      options: ContextMenuOptions(hideDefaultSystemContextMenuItems: true),
      onCreateContextMenu: (hitTestResult) async {
        HapticFeedback.vibrate();
      },
      onHideContextMenu: () {},
    );
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
    _progressCtl.close();
    _titleCtl.close();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (webView != null) {
      if (state == AppLifecycleState.paused) {
        webView.pauseTimers();
        if (Platform.isAndroid) {
          webView.android.pause();
        }
      } else {
        webView.resumeTimers();
        if (Platform.isAndroid) {
          webView.android.resume();
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (await webView.canGoBack()) {
          webView.goBack();
          return false;
        }
        return true;
      },
      child: AnnotatedRegion<SystemUiOverlayStyle>(
        value: SystemUiOverlayStyle.light,
        child: Scaffold(
          appBar: widget.isHiddenTittle == true
              ? null
              : getDefaultAppBar(
                  titleWidget: StreamBuilder<String>(
                    stream: _titleCtl.stream,
                    builder:
                        (BuildContext context, AsyncSnapshot<String> snapshot) {
                      return Text(
                        snapshot.hasData ? snapshot.data : '',
                      );
                    },
                  ),
                  leading: BackButton(
                    onPressed: () async {
                      Navigator.of(context).pop();
                      // try {
                      //   if (await webView?.canGoBack()) {
                      //     webView?.goBack();
                      //   } else {
                      //     Navigator.maybePop(context);
                      //   }
                      // } catch (e) {
                      //   Navigator.of(context).pop();
                      // }
                    },
                  ),
                ),
          body: Column(
            children: <Widget>[
              if (widget.isHiddenTittle == true)
                SizedBox(
                  height: MediaQuery.of(context).padding.top,
                ),
              if (widget.isShowProgress)
                StreamBuilder<double>(
                  stream: _progressCtl.stream,
                  builder:
                      (BuildContext context, AsyncSnapshot<double> snapshot) {
                    if (snapshot.hasData) {
                      return Container(
                          height: getDp(2),
                          child: snapshot.data < 1.0
                              ? LinearProgressIndicator(
                                  value: snapshot.data,
                                  color: aceGreenColor,
                                )
                              : Container());
                    } else {
                      return Container(
                        height: getDp(1),
                      );
                    }
                  },
                ),
              Expanded(
                child: IndexedStack(
                  index: showLoading ? 0 : 1,
                  children: <Widget>[
                    BaseConfig.pageBase.buildLoadingWidget(context),
                    _webView,
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  get _webView => InAppWebView(
        contextMenu: contextMenu,
        initialUrlRequest: URLRequest(url: Uri.parse(widget.url)),
        androidShouldInterceptRequest: null,
        onCreateWindow: _buildWindow,
        initialOptions: InAppWebViewGroupOptions(
          crossPlatform: InAppWebViewOptions(
            supportZoom: false,
            useOnLoadResource: true,
            javaScriptEnabled: true,
            cacheEnabled: true,
            clearCache: true,
            mediaPlaybackRequiresUserGesture: true,
            disableContextMenu: true,
            useShouldOverrideUrlLoading: true,
          ),
          android: AndroidInAppWebViewOptions(
//          domStorageEnabled: true,
//          builtInZoomControls: false,
//          geolocationEnabled: true,
//          allowFileAccessFromFileURLs: true,
//          allowUniversalAccessFromFileURLs: true,
//          displayZoomControls: false,
//          useWideViewPort: true,
//          supportMultipleWindows: true,
//          networkAvailable: true,
            blockNetworkImage: false,
            mixedContentMode:
                AndroidMixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW,
            verticalScrollbarPosition:
                AndroidVerticalScrollbarPosition.SCROLLBAR_POSITION_RIGHT,
          ),
          ios: IOSInAppWebViewOptions(
            allowsInlineMediaPlayback: true,
//              suppressesIncrementalRendering: true,
//              isFraudulentWebsiteWarningEnabled: true,
//              enableViewportScale: false,
//              allowsPictureInPictureMediaPlayback: true,
//              allowsLinkPreview: true,
//              allowsBackForwardNavigationGestures: true,
//              allowsAirPlayForMediaPlayback: true
//            withZoom: false,
//            withLocalStorage: false,
//            hidden: false,
//            withOverviewMode: true,
//            allowFileURLs: true,
//            geolocationEnabled: true,
//            withJavascript: true,
//            clearCache: true,
//            clearCookies: true,
//            displayZoomControls: false,
//            useWideViewPort: true,
//            supportMultipleWindows: true,
//            debuggingEnabled: true,
          ),
        ),
        onWebViewCreated: (_) async {
          webView = _;
        },
        onLoadStart: (controller, url) {
          logger.d('onLoadStart:$url');
        },

        onLoadError: _onLoadError,
        onLoadHttpError: _onLoadHttpError,
        onLoadStop: (InAppWebViewController controller, Uri url) async {
          print("onLoadStop $url");
          controller.evaluateJavascript(source: 'document.title').then((value) {
            logger.d('标题返回：$value');
            _titleCtl.add(value);
          });
        },
        onProgressChanged: (InAppWebViewController controller, int progress) {
          _progressCtl.add(progress / 100);
          if (progress / 100 == 1 && showLoading == true) {
            setState(() {
              showLoading = false;
            });
          }
        },
        shouldOverrideUrlLoading: _onOverrideUrlLoading,
        onUpdateVisitedHistory:
            (InAppWebViewController controller, Uri url, bool androidIsReload) {
//                setState(() {
//                  this.url = url;
//                });
        },
        onExitFullscreen: _onExitFullscreen,
        onEnterFullscreen: _onEnterFullscreen,
        onJsAlert: _onJsAlert,
//        onConsoleMessage:
//            (InAppWebViewController controller, ConsoleMessage consoleMessage) {
//          print("""
//              console output:
//                ${consoleMessage.messageLevel}: ${consoleMessage.toJson()}
//              """);
//        },
      );

  Future<bool> _buildWindow(InAppWebViewController controller,
      CreateWindowAction createWindowAction) async {
    return true;
  }

  Future<NavigationActionPolicy> _onOverrideUrlLoading(
      InAppWebViewController controller,
      NavigationAction navigationAction) async {
    return NavigationActionPolicy.ALLOW;
  }

  void _onExitFullscreen(InAppWebViewController controller) {
    print('退出全屏');
  }

  void _onEnterFullscreen(InAppWebViewController controller) {
    print('进入全屏');
  }

  void _onLoadError(
      InAppWebViewController controller, Uri url, int code, String message) {
    print('onLoadError url:$url , code:$code , message:$message');
  }

  void _onLoadHttpError(InAppWebViewController controller, Uri url,
      int statusCode, String description) {
    print(
        'onLoadHttpError url:$url , statusCode:$statusCode , description:$description');
  }

  Future<JsAlertResponse> _onJsAlert(
      InAppWebViewController controller, JsAlertRequest jsAlertRequest) async {
    print('_onJsAlert:${jsAlertRequest.toJson()}');
    if (jsAlertRequest.message == 'success') {
      bool isAdd = Provider.of<WebViewProvider>(context, listen: false)?.isAdd;
      if (isAdd == true) {
        Navigator.of(context).pop({'isSuccess': true});
      } else {
        bool isSuccess = await showPaySubSuccess(context, onSeeInvoice: () {
          Navigator.of(context).pop(true);
        });
        if (isSuccess == true) {
          Navigator.of(context).pop({'isSeeInvoice': true});
        } else {
          Navigator.of(context).pop({'isSuccess': true});
        }
      }
      return JsAlertResponse(
        message: 'Success',
        handledByClient: true,
      );
    }
    showGotItTipBottomSheet(context, jsAlertRequest.message);
    return JsAlertResponse(
      message: jsAlertRequest.message,
      handledByClient: true,
    );
  }
}
